const mongoose = require('mongoose');

const reviewSchema = new mongoose.Schema({
    // 关联用户
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },

    // 关联车辆
    carId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Car',
        required: true
    },

    // 关联订单
    orderId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Order',
        required: true,
        unique: true  // 一个订单只能评价一次
    },

    // 评分
    rating: {
        type: Number,
        required: true,
        min: 1,
        max: 5
    },

    // 评论内容
    comment: {
        type: String,
        trim: true
    },

    // 创建时间
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// 创建评价后更新车辆的平均评分
reviewSchema.post('save', async function () {
    const Review = this.constructor;
    const Car = mongoose.model('Car');

    // 计算该车辆的新平均评分
    const stats = await Review.aggregate([
        { $match: { carId: this.carId } },
        {
            $group: {
                _id: '$carId',
                averageRating: { $avg: '$rating' },
                count: { $sum: 1 }
            }
        }
    ]);

    // 更新车辆信息
    if (stats.length > 0) {
        await Car.findByIdAndUpdate(this.carId, {
            'rentalHistory.averageRating': stats[0].averageRating,
            'rentalHistory.rentCount': stats[0].count
        });
    }
});

// 修改导出为mongoose模型
module.exports = mongoose.model('Review', reviewSchema); 